import { useState, useEffect, useRef } from "react";

export default function BB() {
  return (
    <>
      <UseState></UseState>
      <UseEffect></UseEffect>
    </>
  );
}
function UseState() {
  let [num, setNum] = useState(0);
  let updateNum = () => {
    setTimeout(() => {
      setNum(num + 1);
    }, 0);
  };
  return (
    <>
      <span>{num}</span>
      <button onClick={updateNum}>num++</button>
    </>
  );
}
function UseEffect() {
  let [num, setNum] = useState(0);
  let numRef = useRef(0);
  let updateNum = () => {
     
    setNum(num + 1);
    numRef.current = num
  };
  useEffect(() => {
    let timer = setInterval(() => {
      console.log(num, "num"); //拿不到最新的值
      console.log(numRef.current, "numRef"); //拿不到最新的值
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, [num]);
  return (
    <>
      <span>{num}</span>
      <button
        onClick={updateNum}
      >
        num++
      </button>
    </>
  );
}
